<?php

namespace App\Http\Controllers;

use App\Models\Org;
use App\Models\Platform;
use App\Models\Project;
use App\Models\Team;
use App\Models\Volunteer;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;

class PlatformController extends Controller
{
    public function __construct(Request $request)
    {
        if (preg_match('#^api/org/term#', $request->path())
            || preg_match('#^api/changchun/info#', $request->path())
        ) {
            parent::__construct();
            return;
        }

        $user = $request->user();

        if (!$user || $user->type != 4 && $user->type != 5) {
            throw new \Exception('权限不足');
        }

        parent::__construct();
    }

    public function index(Request $request)
    {
        $perPage = $request->get('perPage', 10);
        $info = Platform::query();

        if ($request->has('name')) {
            $info->where('name', 'like', '%'.$request->get('name').'%');
        }

        $info = $info->paginate($perPage)->toArray();

        for($i=0; $i<count($info['data']);$i++){
            if(!empty($info['data'][$i]['org_list'])){
                $ids = $info['data'][$i]['org_list'];
                $info['data'][$i]['org_num'] = count($ids);
                $info['data'][$i]['project_num'] = Project::whereIn('org_id',$ids)->count();
                $info['data'][$i]['volunteer_num'] = Volunteer::whereIn('org_id',$ids)->count();
                $info['data'][$i]['volunteer_time'] = Volunteer::whereIn('org_id',$ids)->sum('reward_time');
            }else{
                $info['data'][$i]['org_num'] = 0;
                $info['data'][$i]['project_num'] = 0;
                $info['data'][$i]['volunteer_num'] = 0;
                $info['data'][$i]['volunteer_time'] = 0;
            }
        }
        return $this->returnJSON([
            'count' => $info['total'],
            'rows' => $info['data']
        ]);
    }

    public function show($id)
    {
        $node = Platform::findOrFail($id);
        $data = $node->toArray();

        if (isset($data['user_id'])) {
            $user = User::findOrFail($data['user_id']);
            $data['username'] = $user->username;
            $data['email'] = $user->email;
        }

        $data['modules'] = $data['module_settings'];
        unset($data['module_settings']);

        return $this->returnJSON($data, 0, 'ok');
    }


    public function store(Request $request) {
        $this->validate($request, [
            'name' => 'required|max:32|unique:platform,name',
            'contact_name' => 'required|max:32',
            'contact_phone' => 'required|max:32',
            'contact_email' => 'required|max:255',
            'address' => 'required',
            'corporate_name' => 'required|max:32',
            'corporate_id' => 'required|max:32',
            'corporate_phone' => 'required|max:32',
            'username' => 'required|unique:user|max:64',
            'pwd' => 'required|max:64'
        ]);

        $node = new Platform();
        $data = $request->only([
            'name',
            'logo',
            'contact_name',
            'contact_phone',
            'contact_email',
            'address',
            'corporate_name',
            'corporate_id',
            'corporate_phone',
            'quality',
            'username',
            'pwd',
            'email'
        ]);
        // default values;
        $data['user_id'] = 0;
        $data['logo'] = isset($data['logo']) ? $data['logo'] : '';
        $data['quality'] = isset($data['quality']) ? $data['quality'] : '';
        $data['module_settings'] = [];

        $node->fill($data);

        if ($node->save()) {

            if (isset($data['pwd'])) {
                $user = new User();
                $user->fill([
                    'username' => $data['username'],
                    'pwd' => bcrypt($data['pwd']),
                    'email' => isset($data['email']) ? $data['email'] : '',
                    'type' => 5,
                    'platform_id' => $node->id
                ]);
                $user->save();
                $node->fill([
                    'user_id' => $user->id
                ]);
                $node->save();
            }

            return $this->returnJSON(null, 0, '新增成功');
        }
        return $this->returnJSON(null, 500, '新建失败');
    }

    public function update(Request $request, $id)
    {
        $node = Platform::findOrFail($id);

        $this->validate($request, [
            'name' => ['required', 'max:32', Rule::unique('platform')->ignore($id)],
            'contact_name' => 'required|max:32',
            'contact_phone' => 'required|max:32',
            'contact_email' => 'required|max:255',
            'address' => 'required',
            'corporate_name' => 'required|max:32',
            'corporate_id' => 'required|max:32',
            'corporate_phone' => 'required|max:32',
            'username' => [
                'max:64',
                Rule::unique('user')->ignore($node->user_id)
            ],
            'pwd' => 'max:64'
        ]);

        $data = $request->only([
            'name',
            'logo',
            'contact_name',
            'contact_phone',
            'contact_email',
            'address',
            'corporate_name',
            'corporate_id',
            'corporate_phone',
            'quality',
            'username',
            'pwd',
            'email'
        ]);

        $data = $this->rmNullProps($data);

        if (isset($data['pwd'])) {
            if ($node->user_id) {
                $user = User::findOrFail($node->user_id);
                $user->fill([
                    'username' => $data['username'],
                    'pwd' => bcrypt($data['pwd']),
                    'email' => isset($data['email']) ? $data['email'] : '',
                ]);
                $user->save();
            } else {
                $user = new User();
                $user->fill([
                    'username' => $data['username'],
                    'pwd' => bcrypt($data['pwd']),
                    'email' => isset($data['email']) ? $data['email'] : '',
                    'type' => 5,
                    'platform_id' => $node->id
                ]);
                $user->save();
                $data['user_id'] = $user->id;
            }
        }


        $node->fill($data);
        if ($node->save()) {
            return $this->returnJSON(null, 0, '保存成功');
        }
        return $this->returnJSON(null, 500, '保存失败');
    }

    public function online(Request $request, $id)
    {
        $ids = array_map(function($item) {
            return intval($item);
        }, explode(",", $id));
        $result = Platform::whereIn('id',  $ids)->update(['is_blacklist' => 1]);

        if ($result) {
            return $this->returnJSON($ids, 0, '启用成功');
        } else {
            return $this->returnJSON(null, 1, "启用失败");
        }
    }
    public function offline(Request $request, $id)
    {
        $ids = array_map(function($item) {
            return intval($item);
        }, explode(",", $id));
        $result = Platform::whereIn('id',  $ids)->update(['is_blacklist' => 0]);

        if ($result) {
            return $this->returnJSON($ids, 0, '禁用成功');
        } else {
            return $this->returnJSON(null, 1, "禁用失败");
        }
    }


    public function saveSettings(Request $request, $id) {
        $this->validate($request, [
            'prefix' => ['required', 'max:32', Rule::unique('platform')->ignore($id)],
            'cert_title' => 'required',
            'cert_platform' => 'required',
            'cert_cachet' => 'required',
            'cert_auth_platform' => 'required',
        ]);

        $user = $request->user();

        if (!($user->type === 4)) {
            throw new \Exception('权限不足');
        }

        $node = Platform::find($id);

        $data = $request->only([
            'prefix',

            'org_list',
            'cert_title',
            'cert_platform',
            'cert_cachet',
            'cert_auth_platform',

            'modules',

            'platform_info',
            'platform_manual',
            'platform_service',
            'platform_service_tel',

        ]);
        if (isset($data['modules'])) {
            $data['module_settings'] = $data['modules'];
            unset($data['modules']);
        }

        $node->fill($data);
        if($node->save()){
            return $this->returnJSON($node->toArray(), 0, '保存机构设置成功');
        }
        return $this->returnJSON(null, 0, '操作失败');
    }


    public function orglist(Request $request){
        $perPage = $request->get('perPage', 10);
        $user = $request->user();
        if($user->type != 5){
            return $this->returnJSON(null, 1, "权限不足");
        }
        $org_ids = Platform::where('id',$user->platform_id)->first()->org_list;
        $org_list = Org::whereIn('id',$org_ids);

        $info = $org_list->paginate($perPage)->toArray();

        for($i=0; $i<count($org_ids);$i++){
            $teams = collect(Team::where('org_id',$org_ids[$i])->get());

            $info['data'][$i]['team_num'] = $teams->count();
            $info['data'][$i]['project_num'] = Project::where('org_id',$org_ids[$i])->count();
            $info['data'][$i]['volunteer_num'] = Volunteer::where('org_id',$org_ids[$i])->count();
            $info['data'][$i]['volunteer_time'] = Volunteer::where('org_id',$org_ids[$i])->sum('reward_time');
        }
        return $this->returnJSON([
            'count' => $info['total'],
            'rows' => $info['data']
        ]);
    }


    public function org(Request $request,$id)
    {
        $user = $request->user();
        if($user->type != 4){
            return $this->returnJSON(null, 1, "权限不足");
        }
        $node = Platform::findOrFail($id);
        $ids = $node->org_list;
        $org_sel = new Org();
        $org_unsel = new Org();

        if ($request->has('name')) {
            $org_sel = $org_sel->where('name', 'like', '%'.$request->get('name').'%');
            $org_unsel = $org_unsel->where('name', 'like', '%'.$request->get('name').'%');
        }
        if($request->has('province')){
            if($request->has('city')){
                if($request->has('country')){
                    $org_sel = $org_sel->where(['contact_province_name' => $request->input('province'),'contact_city_name' => $request->input('city'),'contact_county_name', $request->input('district')]);
                    $org_unsel = $org_unsel->where(['contact_province_name' => $request->input('province'),'contact_city_name' => $request->input('city'),'contact_county_name', $request->input('district')]);
                }else{
                    $org_sel = $org_sel->where(['contact_province_name' => $request->input('province'),'contact_city_name' => $request->input('city')]);
                    $org_unsel = $org_unsel->where(['contact_province_name' => $request->input('province'),'contact_city_name' => $request->input('city')]);
                }
            }else{
                $org_sel = $org_sel->where('contact_province_name', $request->input('province'));
                $org_unsel = $org_unsel->where('contact_province_name', $request->input('province'));
            }
        }

        if(empty($ids)){
                $org_sel = "";
                $org_unsel = $org_unsel->where('in_blacklist',0)->get();
        }else{
            $org_sel = $org_sel->whereIn('id',$ids)->get();
            $org_unsel = $org_unsel->whereNotIn('id',$ids)->where('in_blacklist',0)->get();
        }


        return $this->returnJSON([
            'org_sel' => $org_sel,
            'org_unsel' => $org_unsel,
        ]);

    }
}
